package com.dji.swing.model;

import javax.swing.JFrame;

import com.dji.bean.Autowired;
import com.dji.bean.Compoment;
import com.dji.bean.InitializingBean;
import com.dji.bean.Property;
import com.dji.common.utils.UIUtil;
import com.dji.service.model.UserService;
import com.dji.swing.view.BrowserItemView;
import com.dji.swing.view.Windows;
import com.dji.system.core.SystemInit;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.dom.events.DOMEvent;
import com.teamdev.jxbrowser.chromium.dom.events.DOMEventListener;
import com.teamdev.jxbrowser.chromium.dom.internal.Element;

@Compoment
public class BrowEventListener implements DOMEventListener, InitializingBean {
	@Autowired
	private BrowserItemView browserItemView;
	@Autowired
	private Windows windows;
	@Autowired
	private UserService userService;
	@Property("project.path")
	private String projectPath;
	private Browser browser;

	public void handleEvent(DOMEvent e) {
		Element element = (Element) e.getTarget();
		String currentURL = browser.getURL();
		String elementId = element.getAttribute("id");
		String text = element.getInnerText();
		if ("调试模式".equals(text)) {
			element.setInnerText("恢复正常");
			windows.setSize(500, 600);
			UIUtil.setCenter(windows);
		} else if ("恢复正常".equals(text)) {
			element.setInnerText("调试模式");
			windows.setExtendedState(JFrame.MAXIMIZED_BOTH);
		}
		if ("exit".equals(elementId)) {
			SystemInit.exit();
		}
		if (currentURL.endsWith("login.html")) {
			if ("login".equals(elementId)) {
				String userName = browser.executeJavaScriptAndReturnValue("$('#name').val()").getStringValue();
				String passwordk = browser.executeJavaScriptAndReturnValue("$('#password').val()").getStringValue();
				if (userService.login(userName, passwordk)) {
					browser.loadURL(getMainPagePath());
					SystemInit.fingerSearchStart();
				}
			} else if ("fullScreen".equals(elementId)) {

			}
		} else if (currentURL.endsWith("main.html")) {
			if ("mainPage".equals(elementId)) {
				SystemInit.initBrow();
			}
		}
	}

	/**
	 * 获取打卡页面路径
	 * 
	 * @return
	 */
	private String getMainPagePath() {
		StringBuilder mainPath = new StringBuilder("file:///");
		mainPath.append(projectPath);
		if (mainPath.toString().endsWith("/")) {
			mainPath.append("html/main.html");
		} else {
			mainPath.append("/html/main.html");
		}
		return mainPath.toString();
	}

	@Override
	public void afterProPertiesSet() {
		browser = browserItemView.getBrowser();
	}
}
